package com.baidu.utils;



import org.apache.http.HttpResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class DuanXinUtils {

    /**
     * 产生验证码
     * @return
     */
    public static String createCode(){
        //定义验证码字符串
        String yzm="";
//        实例化随机对象
        Random random = new Random();
//        通过for循环，拼接验证码字符串
        for (int i=0;i<4;i++){
//            拼接验证码字符串并设置产生的值的返回为1位数
            yzm+=random.nextInt(10);
        }
//        返回拼接后的验证码
        return yzm;
    }


    public static boolean  sendDuanxin(String phone,String code){
        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        //使用自己的AppCode
        String appcode = "d8591e9db99e4496b96b042fca478a8b";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        //发送给用户的手机号
        querys.put("mobile", phone);
        //发送给手机的验证码
        querys.put("param", "code:"+code);
        //使用短信API市场提供的短信模板
        querys.put("tpl_id", "TP1711063");
        //因为我已经和客服沟通（至少是花钱的5块钱）
//        querys.put("tpl_id", "TP19072321");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            //发送成功，返回true
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

            //如果发送失败，打印异常，返回false
            return false;
    }
}
